﻿using Elasticsearch.Net;
using Microsoft.Extensions.Options;
using Microsoft.VisualBasic.FileIO;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ElasticSearchCore
{
    public class EsClientProvider : IEsClientProvider
    {
        private readonly IOptions<EsConfig> _EsConfig;

        public EsClientProvider(IOptions<EsConfig> esConfig)
        {
            _EsConfig = esConfig;
        }

        ElasticClient IEsClientProvider.GetClient()
        {
            return GetClient(_EsConfig.Value.Urls.ToArray());
        }

        ElasticClient IEsClientProvider.GetClient(string indexName)
        {
            return GetClient(_EsConfig.Value.Urls.ToArray(), indexName);
        }

        private ElasticClient GetClient(string url, string defaultIndex = "")
        {
            var uri = new Uri(url);
            var connectionSetting = new ConnectionSettings(uri);
            if (!string.IsNullOrEmpty(defaultIndex))
            {
                connectionSetting.DefaultIndex(defaultIndex);
            }
            connectionSetting.BasicAuthentication(_EsConfig.Value.User, _EsConfig.Value.Password);
            return new ElasticClient(connectionSetting);
        }

        private ElasticClient GetClient(string[] urls, string defaultIndex = "")
        {
            var uris = urls.Select(url => new Uri(url)).ToArray();
            var connectionPool = new SniffingConnectionPool(uris);
            var connectionSetting = new ConnectionSettings(connectionPool);
            if (!string.IsNullOrEmpty(defaultIndex))
            {
                connectionSetting.DefaultIndex(defaultIndex);
            }
            connectionSetting.BasicAuthentication(_EsConfig.Value.User, _EsConfig.Value.Password);
            return new ElasticClient(connectionSetting);
        }
    }
}
